package org.idea.web.socket.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.idea.web.socket.config.MqProducerConfig;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @Author linhao
 * @Date created in 11:05 上午 2021/5/10
 */
@Configuration
@Slf4j
@EnableConfigurationProperties({MqProducerConfig.class})
public class MqProducerAutoConfig {

    @Resource
    private MqProducerConfig mqProducerConfig;

    @Bean
    @ConditionalOnMissingBean
    //意味着DefaultMQProducer的配置可以被覆盖
    public DefaultMQProducer defaultMQProducer() {
        DefaultMQProducer producer = new DefaultMQProducer(mqProducerConfig.getGroupName());
        producer.setNamesrvAddr(mqProducerConfig.getNameSrvAddr());
        //没有则自动创建topic的key
//        producer.setCreateTopicKey("AUTO_CREATE_TOPIC_KEY");
        producer.setMaxMessageSize(mqProducerConfig.getMaxMessageSize());
        producer.setSendMsgTimeout(mqProducerConfig.getSendMsgTimeout());
        producer.setRetryTimesWhenSendFailed(mqProducerConfig.getRetryTimesWhenSendFailed());
        try {
            producer.start();
            log.info("【 MqProducerAutoConfig 】mq producer is started!");
        } catch (Exception e) {
            log.error("[MqProducerAutoConfig] start fail, e is ", e);
        }
        return producer;
    }
}
